package cn.wolfcode.web.interceptor;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.util.RequiredPermission;
import cn.wolfcode.util.UserContext;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
@Component
public class CheckPermissionInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //从session中获取用户信息
        Employee employee = (Employee) request.getSession().getAttribute("USER_IN_SESSION");
        //判断是否是超管
        if (employee.isAdmin()) {
            return true;
            //放行
        }
        //看handler是不是HandlerMethod的类型,代表被拦截的就是处理方法
        if(handler instanceof HandlerMethod){
            //强转为HandlerMethod
            HandlerMethod method=  (HandlerMethod) handler;
            //获取权限注解
            RequiredPermission methodAnnotation = method.getMethodAnnotation(RequiredPermission.class);
            //判断方法是否有贴注解
            if (methodAnnotation == null) {
                //没贴放行
                return true;
            }
            //贴了就接着获取当前用户拥有的权限
           // List<String> expressions = (List<String>) request.getSession().getAttribute("EXPRESSIONS_IN_SESSION");
            List<String> expressions = UserContext.getExpressions();
            //获取权限注解表达式
            String expression = methodAnnotation.expression();
            if(!expressions.contains(expression)){
                //不包含代表没有权限
                response.sendRedirect("/nopermission");
                return false;
            }
        }
        return true;
        //不放行
    }
}
